package com.cheyunkeji.er.utils;

import com.cheyun.netsalev3.MyApplication;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * Created by zhongzhiwen on 2016/5/6.
 */
public class StrUtil {

    /**
     * 字符串是否为空
     */
    public static boolean isEmpty(String s) {
        return s == null || s.trim().equals("") || s.toLowerCase().equals("null");
    }

    public static String getString(int strId){
       return  MyApplication.getInstance().getResources().getString(strId);
    }

    public String[] getStringArray(int arrayId){
        return MyApplication.getInstance().getResources().getStringArray(arrayId);
    }

    /**
     * 处理unicode字符串
     */
    public static String ascii2native(String asciicode) {
        String[] asciis = asciicode.split("\\\\u");
        String nativeValue = asciis[0];
        try {
            for (int i = 1; i < asciis.length; i++) {
                String code = asciis[i];
                nativeValue += (char) Integer.parseInt(code.substring(0, 4), 16);
                if (code.length() > 4) {
                    nativeValue += code.substring(4, code.length());
                }
            }
        } catch (NumberFormatException e) {
            return asciicode;
        }
        return nativeValue;
    }

    /**
     * 解析JSON中的字符串
     */
    public static String optJSONString(JSONObject obj, String key) {
        String s = obj.optString(key);
        if (isEmpty(s)) {
            return "";
        }
        return s;
    }

    /**
     * 解析JSON中的字符串,如果等于0则返回空字符串
     */
    public static String optJSONStringExceptZero(JSONObject obj, String key) {
        String s = optJSONString(obj, key);
        if (isInteger(s)) {
            int i = Integer.parseInt(s);
            if (i == 0) {
                return "";
            }
        } else if (isDecimal(s)) {
            float f = Float.parseFloat(s);
            if (f == 0f) {
                return "";
            }
        }
        return s;
    }

    /**
     * 解析JSON字符串数组,返回以逗号拼接
     */
    public static String optStringArr(JSONObject obj, String key) {
        String ret = "";

        String arrStr = optJSONString(obj, key);
        if (!StrUtil.isEmpty(arrStr)) {
            try {
                JSONArray array = new JSONArray(arrStr);
                for (int i = 0; i < array.length(); i++) {
                    if (StrUtil.isEmpty(ret)) {
                        ret += array.getString(i);
                    } else {
                        ret += "," + array.getString(i);
                    }
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
        return ret;
    }

    /**
     * 解析时间数组,数组中第一个为时间戳
     */
    public static long optTimeByJSONArray(JSONObject obj, String key) {
        try {
            JSONArray array = new JSONArray(optJSONString(obj, key));
            if (array.length() > 0) {
                return Long.parseLong(array.getString(0));
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return 0;
    }

    /**
     * 字符串是否为整型
     */
    public static boolean isInteger(String str) {
        if (!StrUtil.isEmpty(str)) {
            Pattern pattern = Pattern.compile("^[-\\+]?[\\d]+$");
            return pattern.matcher(str).matches();
        }
        return false;
    }

    /**
     * 字符串是否为小数
     */
    public static boolean isDecimal(String str) {
        if (!StrUtil.isEmpty(str)) {
            Pattern pattern = Pattern.compile("^[-\\+]?[\\d]+\\.[\\d]+$");
            return pattern.matcher(str).matches();
        }
        return false;
    }

    /**
     * string转int
     */
    public static int strToInt(String s) {
        int ret = 0;
        if (!isEmpty(s) && isInteger(s)) {
            ret = Integer.parseInt(s);
        }
        return ret;
    }

    /**
     * 获取字符串中某个字符出现的次数
     */
    public static int getCharC(String value, char target) {
        int ret = 0;
        for (int i = 0; i < value.length(); i++) {
            if (value.charAt(i) == target) {
                ret++;
            }
        }
        return ret;
    }

    /**
     * 手机号是否合法
     */
    public static boolean isMobileNO(String mobiles) {
        Pattern p = Pattern.compile("^1\\d{10}$");
        Matcher m = p.matcher(mobiles);
        return m.matches();
    }

    /**
     * 密码是否合法
     */
    public static boolean isUseablePwd(String pwd) {
        Pattern p = Pattern.compile("^[^\\s]{6,12}$");
        Matcher m = p.matcher(pwd);
        return m.matches();
    }

    /**
     * 获取文件名("/"之后的最后一个字符串)
     */
    public static String getLastName(String url) {
        String name = "";
        String[] ss = url.split("/");
        if (ss.length > 0) {
            name = ss[ss.length - 1];
        }
        return name;
    }

    /**
     * 截取字符串,保留n个字符,多出的部分以…代替
     */
    public static String cutString(String s, int n) {
        if (n > 0 && s.length() > n) {
            s = s.substring(0, n) + "…";
        }
        return s;
    }

    /**
     * 隐藏手机中间四位
     */
    public static String hidePhone(String s) {
        if (s.length() == 11) {
            String m_s = s.substring(3, 7);
            s = s.replace(m_s, "****");
        }
        return s;
    }

    /**
     * 字节数转换为MB
     */
    public static float byteToMB(long c) {
        return (float) c / 1048576f;
    }

    /**
     * 获取hashmap的id集合,以逗号分隔
     */
    public static String getIdsStrByHashMap(HashMap<String, String> hashMap) {
        String s = "";
        for (String key : hashMap.keySet()) {
            if (StrUtil.isEmpty(s)) {
                s += key;
            } else {
                s += "," + key;
            }
        }
        return s;
    }

    /**
     * 获取hashmap的value集合,以逗号分隔
     */
    public static String getValuesStrByHashMap(HashMap<String, String> hashMap) {
        String s = "";
        for (String key : hashMap.keySet()) {
            if (StrUtil.isEmpty(s)) {
                s += hashMap.get(key);
            } else {
                s += "," + hashMap.get(key);
            }
        }
        return s;
    }

    /**
     * 根据字符串返回hashmap,字符串以逗号分隔
     */
    public static HashMap<String, String> getHashMapByIdsStr(String keys, String values) {
        HashMap<String, String> hm = new HashMap<>();
        String[] ssKeys = keys.split(",");
        String[] ssValues = values.split(",");
        for (int i = 0; i < ssKeys.length && i < ssValues.length; i++) {
            if (!StrUtil.isEmpty(ssKeys[i]) && !StrUtil.isEmpty(ssValues[i])) {
                hm.put(ssKeys[i], ssValues[i]);
            }
        }
        return hm;
    }

    /**
     * 字符串数组中指定的字符串是否存在
     */
    public static boolean isIn(String find, String... target) {
        for (String s : target) {
            if (!StrUtil.isEmpty(s) && s.equals(find)) {
                return true;
            }
        }
        return false;
    }

    public static boolean isIn(int find, int... target) {
        for (int i : target) {
            if (i == find) {
                return true;
            }
        }
        return false;
    }

    /**
     * 将json对象的各个字段添加到hashmap中
     */
    public static void addJSON(HashMap<String, String> hashMap, JSONObject obj) throws JSONException {
        Iterator keyIter = obj.keys();
        while (keyIter.hasNext()) {
            String key = keyIter.next().toString();
            String value = obj.getString(key);

            hashMap.put(key, value);
        }
    }

    /**
     * 将json数组的各个对象添加到arrayList中
     */
    public static void addJSON(ArrayList<String> arrayList, JSONArray jsonArray) throws JSONException {
        for (int i = 0; i < jsonArray.length(); i++) {
            arrayList.add(jsonArray.get(i).toString());
        }
    }

    /**
     * 新加方法处理成交榜的 成交率 数据(加%号，保留两位小数，四舍五入)
     * @param arrayList
     * @param jsonArray
     * @param jsonType
     * @throws JSONException
     */
    public static void addJSON(ArrayList<String> arrayList, JSONArray jsonArray,String jsonType) throws JSONException {
        for (int i = 0; i < jsonArray.length(); i++) {
            if( i == jsonArray.length() -1){
//                Log.e("成交率", "addJSON: "+"=====================");
//                Log.e("成交率", "addJSON: "+jsonArray.get(i));
                arrayList.add(StrUtil.getRateNumberWitdhPercentChar(jsonArray.get(i)));
                continue;
            }
            arrayList.add(jsonArray.get(i).toString());
//            Log.e("成交率", "addJSON: "+jsonArray.get(i));
        }
    }

    /**
     * 从JSONObject中提取数据,过滤掉uid 字段
     * @param arrayList
     * @param object
     * @throws JSONException
     */
    public static void addJSONFromJSONObj(ArrayList<String> arrayList,JSONObject object)throws JSONException{
       for(int i = 1 ; i < object.length()-1;i++){
           if(i == 1){
               arrayList.add(object.optString(i+""));
               continue;
           }
           if(i == 6){
               DecimalFormat df  = new DecimalFormat("######0.00");
               arrayList.add(df.format(object.optDouble(i+"")*1.00f)+"%");
               continue;
           }
           arrayList.add(object.optInt(i+"")+"");
//           Log.e(StrUtil.class.getSimpleName(), "addJSONFromJSONObj: "+arrayList.get(i-1));
       }
    }

    public static String getRateNumberWitdhPercentChar(Object number){
            if(number instanceof Integer ){
                return new DecimalFormat("######0.00").format((Integer)number * 1.00f)+"%";
            }else if(number instanceof Double){
                return new DecimalFormat("######0.00").format((Double) number * 1.00f)+"%";
            }else if(number instanceof Float){
                return new DecimalFormat("######0.00").format((Float) number * 1.00f)+"%";
            }
        return "";
    }

    public static JSONArray jsonArrayRemove(JSONArray array, int index) {
        JSONArray jsonArray = new JSONArray();
        for (int i = 0; i < array.length(); i++) {
            if (i == index) {
                continue;
            } else {
                try {
                    jsonArray.put(array.get(i));
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        }
        return jsonArray;
    }

    public static String optDecimal(String s) {
        if (isDecimal(s)) {
            DecimalFormat df = new DecimalFormat("#0.00");
            s = df.format(Float.parseFloat(s));
        }
        return s;
    }

    public static String cutBbHeaderRedundant(String s) {
        String[] ss = s.split(":");
        if (ss.length > 1) {
            s = ss[0];
        }
        return s;
    }

}
